package com.zhugang.week13.hash;

import java.util.HashMap;
import java.util.Map;

/**
 * @program algorithms
 * @description: twoSum
 * @author: chanzhugang
 * @create: 2022/12/02 17:13
 */
public class TwoSum {

    /**
     * 1、两数之和
     * https://leetcode.cn/problems/two-sum/
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        // 暴力枚举
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{};
    }

    public int[] twoSum2(int[] nums, int target) {
        // 找值问题第一时间要想到哈希表
        // 哈希表作为缓存，不需要先for一遍存map
        Map<Integer, Integer> cache = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (cache.containsKey(target - nums[i])) {
                Integer index = cache.get(target - nums[i]);
                return new int[]{index, i};
            }
            cache.put(nums[i], i);
        }
        return new int[]{};
    }

    public static void main(String[] args) {
        TwoSum twoSum = new TwoSum();
        int[] nums = {2, 7, 11, 15};
        int[] result = twoSum.twoSum2(nums, 9);
        for (int index : result) {
            System.out.println(index);
        }
    }
}